
import Axios, { AxiosRequestConfig } from 'axios'

Axios.defaults.baseURL = process.env.VUE_APP_BASEURL
Axios.defaults.timeout = 8000
Axios.defaults.withCredentials = true

// 请求拦截器
Axios.interceptors.request.use(config => {

  config.headers = {
    'Content-Type': 'application/json;charset=UTF-8'
  }
  return config

}, error => {

  return Promise.reject(error)

})

// 响应拦截器
Axios.interceptors.response.use(
  response => {

    const oData = response.data
    if (response.status === 200 && oData.code === 200) {

      return Promise.resolve(oData.data)

    }
    return Promise.reject(oData)

  },
  // 服务器状态码不是200的情况
  error => {

    return Promise.reject(error.response || {
      msg: '服务失败'
    })

  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url: string, params?: any) {

  return Axios.get(url, {
    params: params
  })

}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url: string, params: any, config: AxiosRequestConfig<any> | undefined) {

  config = Object.assign({ showLoading: true }, config)
  return Axios.post(url, params, config)

}

export default Axios
